/**
 * Created by Administrator on 2018/7/19.
 */
var dataInit;
var quoteDatagrid;
var projId;
var totalmoney = 0;
var randomId;
$$scope.file = {}


// 商务报价条目管理显示隐藏
function showprice() {
    $$scope.item = {};
    $$scope.retainPrice = 0.00;
    $(".hideprice").show();
    $$scope.$apply();
}

function down(uploadPath) {
    $CertusFormAjax.download("attachmentDownBusiness", "uploadFilePath=" + uploadPath);
}


$$scope.businessQuoteApprove = function () {
    //调用公共方法 上传文件
    fileUpload($$scope,
        function (res) {
            $$scope.business.originReason = 'approval';
            $$scope.business.uploadFilePath = res.data;
            $$scope.business.templateCode = 'SWBJLC';
            $$scope.business.quotes = dataInit.exhibitDatas;
            $$scope.business.projId = projId;
            $CertusJsonAjax.ajax("secondBusinessQuote", $$scope.business, function (res) {
                history.back();
            })
        },
        function () {
            layer.msg("请勿上传空文件");
        })
}

var fileInstantiation = {
    classCateCode: 'NBCPYZ',
    fileClassCode: 'TBSWWD'
}
var fileInstantiationDisable = {
    classCateCodeDis: true, //文件类目不可修改
    fileClassCodeDis: true //文件类型不可修改
}
//调用初始化方法
initFileUpload($$scope, fileInstantiation, fileInstantiationDisable, $CertusFormAjax);
//originReason veto promise denied approval

// 商务报价-历史记录
var piclogColumns = [{
    id: 'createTime',
    title: '提交日期',
    width: 100,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var date = new Date(record.createTime);
        var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd hh:mm");
        return content;
    }
}, {
    id: 'createUserName',
    title: '提交人',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
}, {
    id: 'totalBusinessQuatation',
    title: '商务报价总价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
    }
}, {
    id: 'businessInfoPredict',
    title: '商务信息预测',
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'applyDesc',
    title: '申请说明',
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'originReason',
    title: '审批结果',
    type: 'finish',
    width: 100,
    codeTable: status,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        if (value == 'denied') {
            content += '<span style="background:#d9534f;padding:2px 10px;color:white;">未通过</span>';
        }
        if (value == 'promise') {
            content += '<span style="background:#5cb85c;padding:2px 10px;color:white;">已通过</span>';
        }
        return content;
    }
}, {
    id: 'operation',
    title: '报价文件',
    width: 100,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '<button class="btn btn-xs btn-info" onclick="down(\'' + record.uploadFilePath + '\');"><i class="icon-cloud-download"></i>  下载</button>';
        return content;
    }
}];

var quoteItemPronum = [{
    id: 'category',
    title: '分类',
    width: 160,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        return getQuoteItem(value);
    }
}, {
    id: 'cataPrice',
    title: '目录价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
    }
}, {
    id: 'discountedRate',
    title: '折扣率',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = value + '%';
        return content;
    }
}, {
    id: 'discountPrice',
    title: '折后价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
    }
}, {
    id: 'taxRate',
    title: '税率',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = value + '%';
        return content;
    }
}, {
    id: 'taxPrice',
    title: '含税价',
    type: 'string',
    width: 100,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '￥' + value + '元';
        return content;
    }
}, {
    id: 'descriptor',
    title: '说明',
    type: 'string',
    columnClass: 'text-left',
}, {
    id: 'operation',
    title: '操作',
    width: 150,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '<button class="btn btn-xs btn-info" onclick="modifiedQuoteItem(\'' + record.randomId + '\');"><i class="fa fa-edit"></i>  编辑</button>';
        content += '  ';
        content += '<button class="btn btn-xs btn-danger" onclick="delQuoteItem(\'' + record.randomId + '\');"><i class="fa fa-trash-o"></i>  删除</button>';
        randomId = record.randomId;
        return content;

    }
}];

function delQuoteItem(id) {
    // $CertusFormAjax.ajax("deleteQuoteItem", {quoteItemId: id}, function (res) {
    //     if (res.data = "success") {
    //         dataInit.refresh(true);
    //     }
    // })
    layer.confirm('确认删除此数据？', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        for (var i in dataInit.exhibitDatas) {
            if (parseInt(dataInit.exhibitDatas[i].randomId) == parseInt(id)) {
                $$scope.item = dataInit.exhibitDatas[i];
                // totalmoney -= to2fixed(($$scope.item.cataPrice*$$scope.item.discountedRate/100)*(1+$$scope.item.taxRate/100));
                // $$scope.retainPrice = to2fixed(($$scope.item.cataPrice*$$scope.item.discountedRate/100)*(1+$$scope.item.taxRate/100));
                // $$scope.business.totalBusinessQuatation = totalmoney;
                $$scope.$apply();
            }
        }

        randomId = id;
        dataInit.exhibitDatas = dataInit.exhibitDatas.filter(isDiffQuote);
        $$scope.caculateTotal(dataInit.exhibitDatas);
        dataInit.refresh(false);
        $$scope.$apply();
        layer.msg('删除成功');
    });

}

function modifiedQuoteItem(id) {


    for (var i in dataInit.exhibitDatas) {
        if (parseInt(dataInit.exhibitDatas[i].randomId) == parseInt(id)) {
            $(".hideprice").show();
            $$scope.item = dataInit.exhibitDatas[i];
            // totalmoney -= to2fixed(($$scope.item.cataPrice*$$scope.item.discountedRate/100)*(1+$$scope.item.taxRate/100));
            // $$scope.retainPrice = to2fixed(($$scope.item.cataPrice*$$scope.item.discountedRate/100)*(1+$$scope.item.taxRate/100));
            // $$scope.business.totalBusinessQuatation = totalmoney;
            $$scope.$apply();
        }
    }
}

//文件上传统一字段
function showfile() {
    $(".hidefile").show();
}

function getQuoteItem(id) {
    if (id == "1") {
        return "软件";
    } else if (id == "2") {
        return "软件license";
    } else if (id == "3") {
        return "硬件";
    } else if (id == "4") {
        return "服务";
    } else if (id == "5") {
        return "软件定制";
    } else if (id == "6") {
        return "一次性折扣";
    }
}

function downLoadFile() {
    $CertusFormAjax.download("attachmentDownBusiness", "uploadFilePath=" + $$scope.business.uploadFilePath);
}
var randomId;
function isDiffQuote(element) {
    return parseInt(element.randomId) != parseInt(randomId);
}


$$scope.caculateTotal = function (datas) {

    if (this.socket.connected) {

        this.socket.emit("caculateTotal", datas);
    }
}

//方法 被调用时 建立 连接
$$scope.socket = $CertusJsonAjax.socketNode("businessTotalPrice", "", function (socket) {
    socket.on("connection", function (msg, b, c) {
        console.log("connection created");
    })
    socket.on("message", function (data, b, c) {

        if (socket.id == data) {
            $CertusJsonAjax.ajax("businessQuotationBaseInfo", {
                "processInstanceId": $CertusJsonAjax.getProInstanceId(),
                "stepInstanceId": $CertusJsonAjax.getStepInstanceId()
            }, function (res) {
                if (res.data) {
                    projId = res.data.business.projId;
                    $$scope.item = {projId: projId};
                    $$scope.business = res.data.business;

                    // totalmoney = to2fixed($$scope.business.totalBusinessQuatation);
                    //初始化 已通过 报价 或者 未通过报价
                    $$scope.business.proInstanceId = $CertusJsonAjax.getProInstanceId();
                    $$scope.business.stepInstanceId = $CertusJsonAjax.getStepInstanceId();
                    //报价条目 datagrid
                    dataInit = $CertusJsonAjax.dataInit("quoteItemList", {bqCode: $$scope.business.bqCode}, quoteItemPronum, 'priceContainer', 'priceToolBarContainer');


                    //初始化 报价条目 下拉选择框
                    $$scope.categorySelect = [
                        {categoryName: '软件', category: "1"},
                        {categoryName: '软件license', category: "2"},
                        {categoryName: '硬件', category: "3"},
                        {categoryName: '服务', category: "4"},
                        {categoryName: '软件定制', category: "5"},
                        // {categoryName: '一次性折扣', category: "6"}
                    ];

                    $$scope.hideprice = function (retainPrice) {

                        $$scope.item.projId = projId;
                        // totalmoney += to2fixed(retainPrice);
                        // $$scope.business.totalBusinessQuatation = totalmoney;
                        $$scope.caculateTotal(dataInit.exhibitDatas);
                        $(".hideprice").hide();
                    }

                    var fileInstantiation = {
                        classCateCode: 'NBCPYZ',
                        fileClassCode: 'TBSWWD'
                    }
                    var fileInstantiationDisable = {
                        classCateCodeDis: true, //文件类目不可修改
                        fileClassCodeDis: true //文件类型不可修改
                    }
                    //调用初始化方法
                    initFileUpload($$scope, fileInstantiation, fileInstantiationDisable, $CertusFormAjax);

                    $$scope.businessQuoteSubmitSecond = function () {
                        //调用公共方法 上传文件
                        if (dataInit.exhibitDatas && dataInit.exhibitDatas.length > 0) {
                            fileUpload($$scope,
                                function (res) {
                                    $$scope.business.originReason = 'approval';
                                    $$scope.business.uploadFilePath = res.data;
                                    $$scope.business.templateCode = 'SWBJLC';
                                    $$scope.business.quotes = dataInit.exhibitDatas;
                                    ;
                                    $CertusJsonAjax.ajax("secondBusinessQuote", $$scope.business, function (res) {
                                        history.back();
                                    })
                                },
                                function () {
                                    $$scope.business.originReason = 'approval';
                                    $$scope.business.uploadFilePath = $$scope.business.uploadFilePath;
                                    $$scope.business.templateCode = 'SWBJLC';
                                    $$scope.business.quotes = dataInit.exhibitDatas;
                                    $CertusJsonAjax.ajax("secondBusinessQuote", $$scope.business, function (res) {
                                        history.back();
                                    })
                                })
                        } else {
                            layer.msg("请填写报价条目");
                        }


                    }

                    //报价数据
                    quoteDatagrid = $CertusJsonAjax.dataInit("businessQuoteList", {projId: projId}, piclogColumns, "piclogContainer", "piclogToolBarContainer")

                    $$scope.classfictionselect = [
                        {name: '内部保密', value: "0"},
                        {name: '内部公开', value: "1"},
                        {name: '完全公开', value: "2"},
                        {name: '请选择', value: "xxxx"}
                    ];

                    $$scope.rangeSelect = [
                        {name: '请选择', value: "xxxx"},
                        {name: '公司内部', value: "0"},
                        {name: '公开信息', value: "1"}
                    ]

                    $$scope.permissionSelect = [
                        {name: '请选择', value: "xxxx"},
                        {name: '总经理', value: "0"},
                        {name: '总监', value: "1"},
                        {name: '本部门', value: "2"}
                    ]

                    var picker2 = $('#datetime').datetimepicker({
                        format: 'YYYY-MM-DD',
                        locale: moment.locale('zh-cn')
                    }).on('dp.change', function (e) {
                        var result = new moment(e.date).format('YYYY-MM-DD');
                        if (result && !angular.isUndefined(result)) {
                            $$scope.file.validity = result;
                            $$scope.$apply();
                        }
                    })
                }
            })
        } else {
            $$scope.business.totalBusinessQuatation = data.total;
            dataInit.exhibitDatas = data.datas;
            dataInit.refresh(false);
            $$scope.$apply();
        }
    })
});

$$scope.quoteItemSubmit = function () {
    if (certusValidateNotnullPolyfill()) {
        // $$scope.item.taxPrice = to2fixed(($$scope.item.cataPrice*$$scope.item.discountedRate/100)*(1+$$scope.item.taxRate/100));
        // $$scope.item.discountPrice = to2fixed( $$scope.item.cataPrice * $$scope.item.discountedRate / 100);
        // CertusJsonAjax.ajax("quoteItemSubmit", $$scope.item, function (res) {
        //     if (res.data && res.data == "success") {
        //         $$scope.item = {projId: projId};
        //         $(".hideprice").hide();
        //         dataInit.refresh(true);
        //     }
        // })
        randomId = $$scope.item.randomId;
        dataInit.exhibitDatas = dataInit.exhibitDatas.filter(isDiffQuote);

        // dataInit.refresh(false);

        // totalmoney += $$scope.item.taxPrice
        // $$scope.business.totalBusinessQuatation = totalmoney;

        $$scope.item.randomId = biId++;
        dataInit.exhibitDatas.push($$scope.item);
        $$scope.caculateTotal(dataInit.exhibitDatas)
        dataInit.refresh(false);
        $(".hideprice").hide();
    }
}
